<template>
  <div class="base-countdown" :class="{ 'playing': playing, 'red': num <= 3 }">{{ num }}</div>
</template>

<script>

export default {
  name: 'base-countdown',
  props: {
    // 倒计时秒数，默认为 60s
    sec: {
      type: Number,
      default: 60,
    },
    playState: {
      type: String,
      default: 'end', // play | pause | end
    },
    // 是否自动开启倒计时
    autoPlay: {
      type: Boolean,
      default: false,
    },
    // 是否循环播放倒计时
    isLoop: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      num: 0,
      timer: null,
    };
  },
  computed: {
    playing() {
      return this.playState === 'play';
    },
  },
  watch: {
    sec: {
      handler(n) {
        if (n) {
          this.num = n;
        }
      },
      immediate: true,
    },
    playState: {
      handler(state) {
        switch (state) {
          // 开始
          case 'play':
            if (this.num === 0) {
              this.num = this.sec;
            }
            this.start();
            break;

          // 暂停
          case 'pause':
            this.stop('pause');
            break;

          // 重新开始，倒计时恢复初始值
          case 'restore':
            this.num = this.sec;
            this.$emit('update:playState', 'play');
            break;

          // 结束
          case 'end':
            this.num = 0;
            this.stop('end');
            break;
        }
      },
      immediate: true,
    },
  },
  mounted() {
    if (this.autoPlay) {
      this.$emit('update:playState', 'play');
    }
  },
  destroyed() {
    clearTimeout(this.timer);
    this.timer = null;
  },
  methods: {
    /**
     * 开始倒计时
     */
    start() {
      if (this.timer) {
        clearTimeout(this.timer);
      }

      this.timer = setTimeout(() => {
        if (this.num <= 0) {
          this.stop();
          this.$emit('change', this.num, 'end');
          // 是否循环倒计时
          if (this.isLoop) {
            this.$emit('update:playState', 'restore');
          }
          return;
        }
        this.num --;
        this.$emit('change', this.num, this.playState);
        this.start();
      }, 1000);
    },

    /**
     * 停止倒计时
     */
    stop(state = 'end') {
      clearTimeout(this.timer);
      this.timer = null;
      this.$emit('update:playState', state);
    },
  },
};
</script>

<style lang="scss" scoped>
.base-countdown {
  display: inline-block;
  padding: 6px 24px;
  border: 1px solid #ddd;
  border-radius: 4px;

  &.playing {
    color: #00a6c9;
    border-color: #00a6c9;
  }

  &.red {
    color: #f00;
    border-color: #f00;
  }
}
</style>
